// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/functions/sparksql/decimal_util.h>
#include <pollux/testing/gtest_utils.h>

namespace kumo::pollux::functions::sparksql::test {
namespace {

class DecimalUtilTest : public testing::Test {
 protected:
  template <typename R, typename A, typename B>
  void testDivideWithRoundUp(
      A a,
      B b,
      int32_t aRescale,
      R expectedResult,
      bool expectedOverflow) {
    R r;
    bool overflow = false;
    DecimalUtil::divideWithRoundUp<R, A, B>(r, a, b, aRescale, overflow);
    ASSERT_EQ(overflow, expectedOverflow);
    ASSERT_EQ(r, expectedResult);
  }
};
} // namespace

TEST_F(DecimalUtilTest, divideWithRoundUp) {
  testDivideWithRoundUp<int64_t, int64_t, int64_t>(60, 30, 3, 2000, false);
  testDivideWithRoundUp<int64_t, int64_t, int64_t>(
      6, pollux::DecimalUtil::kPowersOfTen[17], 20, 6000, false);
}

TEST_F(DecimalUtilTest, minLeadingZeros) {
  auto result =
      DecimalUtil::minLeadingZeros<int64_t, int64_t>(10000, 6000000, 10, 12);
  ASSERT_EQ(result, 1);

  result = DecimalUtil::minLeadingZeros<int64_t, int128_t>(
      10000, 6'000'000'000'000'000'000, 10, 12);
  ASSERT_EQ(result, 16);

  result = DecimalUtil::minLeadingZeros<int128_t, int128_t>(
      pollux::DecimalUtil::kLongDecimalMax,
      pollux::DecimalUtil::kLongDecimalMin,
      10,
      12);
  ASSERT_EQ(result, 0);
}

TEST_F(DecimalUtilTest, bounded) {
  auto testBounded = [](uint8_t rPrecision,
                        uint8_t rScale,
                        std::pair<uint8_t, uint8_t> expected) {
    ASSERT_EQ(DecimalUtil::bounded(rPrecision, rScale), expected);
  };

  testBounded(10, 3, {10, 3});
  testBounded(40, 3, {38, 3});
  testBounded(44, 42, {38, 38});
}
} // namespace kumo::pollux::functions::sparksql::test
